<template>
  <div class="dashboard-container">
    <!-- 统计卡片区域 -->
    <el-row :gutter="12" class="stats-cards">
      <el-col :xs="12" :sm="6" :md="6" v-for="(stat, index) in statistics" :key="index">
        <el-card class="stat-card" shadow="never" :body-style="{ padding: '0' }">
          <div class="stat-item">
            <div class="stat-left">
              <div class="stat-number">{{ stat.value }}</div>
              <div class="stat-label">{{ stat.label }}</div>
            </div>
            <div class="stat-right">
              <div class="stat-icon" :style="{ background: stat.gradient }">
                <i :class="stat.icon"></i>
              </div>
              <div class="stat-change" :class="stat.changeType">
                <i :class="stat.changeIcon"></i>
                {{ stat.change }}
              </div>
            </div>
          </div>
          <div class="stat-progress">
            <div class="progress-bar" :style="{ background: stat.color, width: stat.progress + '%' }"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 主要内容区域 -->
    <el-row :gutter="12" class="main-content">
      <!-- 左侧区域 -->
      <el-col :xs="24" :lg="16">
        <!-- 图表区域 -->
        <el-row :gutter="12" class="charts-section">
          <!-- 文章趋势图 -->
          <el-col :xs="24" :md="14">
            <el-card class="chart-card trend-card" shadow="never" :body-style="{ padding: '0' }">
              <div class="card-header">
                <div class="header-left">
                  <h3>文章发布趋势</h3>
                  <p>最近7天数据统计</p>
                </div>
              </div>
              <div ref="weeklyChart" class="chart-container"></div>
            </el-card>
          </el-col>

          <!-- 栏目分布图 -->
          <el-col :xs="24" :md="10">
            <el-card class="chart-card pie-card" shadow="never" :body-style="{ padding: '0' }">
              <div class="card-header">
                <div class="header-left">
                  <h3>栏目分布</h3>
                  <p>文章数量占比</p>
                </div>
              </div>
              <div ref="categoryChart" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 最新文章区域 -->
        <el-card class="content-card latest-articles" shadow="never" :body-style="{ padding: '0' }">
          <div class="card-header">
            <div class="header-left">
              <h3>最新文章</h3>
              <p>最近发布的内容</p>
            </div>
            <div class="header-right">
              <el-button type="text" size="small" @click="handleNavigation('/archives')" class="view-all-btn">
                查看全部 <i class="el-icon-arrow-right"></i>
              </el-button>
            </div>
          </div>
          <div class="article-list">
            <div 
              v-for="(article, index) in displayArticles" 
              :key="article.id" 
              class="article-item"
              @click="handleArticleClick(article.id)"
            >
              <div class="article-info">
                <h4 class="article-title">{{ article.title }}</h4>
                <div class="article-meta">
                  <span class="category">{{ article.category?.name || '未分类' }}</span>
                  <span class="date">{{ formatDate(article.createdAt) }}</span>
                </div>
              </div>
              <div class="article-status">
                <el-tag :type="getStatusType(article.status)" size="small">
                  {{ getStatusText(article.status) }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧边栏 -->
      <el-col :xs="24" :lg="8">
        <!-- 热门文章排行 -->
        <el-card class="sidebar-card popular-rank" shadow="never" :body-style="{ padding: '0' }">
          <div class="card-header">
            <div class="header-left">
              <h3>热门排行</h3>
              <p>浏览量最高的文章</p>
            </div>
          </div>
          <div class="rank-list">
            <div 
              v-for="(article, index) in displayPopularArticles" 
              :key="article.id" 
              class="rank-item"
              @click="handleArticleClick(article.id)"
            >
              <div class="rank-number" :class="getRankClass(index)">
                {{ index + 1 }}
              </div>
              <div class="rank-content">
                <div class="rank-title">{{ article.title }}</div>
                <div class="rank-meta">
                  <span class="views">{{ article.views || 0 }} 次浏览</span>
                  <span class="date">{{ formatDate(article.createdAt) }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 系统状态 -->
        <el-card class="sidebar-card system-status" shadow="never" :body-style="{ padding: '0' }">
          <div class="card-header">
            <div class="header-left">
              <h3>系统状态</h3>
              <p>服务运行监控</p>
            </div>
          </div>
          <div class="status-list">
            <div class="status-item">
              <div class="status-info">
                <span class="status-label">数据库连接</span>
                <span class="status-value">正常</span>
              </div>
              <div class="status-indicator success"></div>
            </div>
            <div class="status-item">
              <div class="status-info">
                <span class="status-label">内存使用率</span>
                <span class="status-value">68%</span>
              </div>
              <div class="status-progress">
                <div class="progress-fill" style="width: 68%"></div>
              </div>
            </div>
            <div class="status-item">
              <div class="status-info">
                <span class="status-label">磁盘空间</span>
                <span class="status-value">45%</span>
              </div>
              <div class="status-progress">
                <div class="progress-fill" style="width: 45%"></div>
              </div>
            </div>
            <div class="status-item">
              <div class="status-info">
                <span class="status-label">今日访问</span>
                <span class="status-value">2,341</span>
              </div>
              <div class="status-indicator success"></div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { 
  getStatistics, 
  getRecentArticlesDetailed, 
  getPopularArticlesDetailed,
  getCategoryStats,
  getWeeklyStats 
} from '@/api/dashboard'

const router = useRouter()

// 响应式数据
const statistics = ref([])
const recentArticles = ref([])
const popularArticles = ref([])
const categoryStats = ref([])
const weeklyStats = ref([])

// Chart refs
const weeklyChart = ref(null)
const categoryChart = ref(null)

// Chart instances
let weeklyChartInstance = null
let categoryChartInstance = null

// ResizeObserver（更稳的自适应）
let ro = null
const mountResizeObserver = () => {
  if (typeof ResizeObserver === 'undefined') return
  ro = new ResizeObserver(() => {
    if (weeklyChartInstance) weeklyChartInstance.resize()
    if (categoryChartInstance) categoryChartInstance.resize()
  })
  if (weeklyChart.value) ro.observe(weeklyChart.value)
  if (categoryChart.value) ro.observe(categoryChart.value)
}

// 计算属性 - 限制显示数量，避免内部滚动
const displayArticles = computed(() => recentArticles.value.slice(0, 4))
const displayPopularArticles = computed(() => popularArticles.value.slice(0, 5))

// 数据加载
const loadDashboardData = async () => {
  try {
    const [statsRes, articlesRes, popularRes, categoryRes, weeklyRes] = await Promise.all([
      getStatistics(),
      getRecentArticlesDetailed(4),
      getPopularArticlesDetailed(5),
      getCategoryStats(),
      getWeeklyStats()
    ])

    const statsData = statsRes.data
    statistics.value = [
      {
        label: '总文章数',
        value: statsData.totalArticles || 0,
        icon: 'el-icon-document',
        color: '#409eff',
        gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        change: '+12%',
        changeType: 'positive',
        changeIcon: 'el-icon-caret-top',
        progress: 75
      },
      {
        label: '总栏目数',
        value: statsData.totalCategories || 0,
        icon: 'el-icon-folder',
        color: '#67c23a',
        gradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
        change: '+5%',
        changeType: 'positive',
        changeIcon: 'el-icon-caret-top',
        progress: 60
      },
      {
        label: '总用户数',
        value: statsData.totalUsers || 0,
        icon: 'el-icon-user',
        color: '#e6a23c',
        gradient: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
        change: '+8%',
        changeType: 'positive',
        changeIcon: 'el-icon-caret-top',
        progress: 85
      },
      {
        label: '总浏览量',
        value: statsData.totalViews || 0,
        icon: 'el-icon-view',
        color: '#f56c6c',
        gradient: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
        change: '+15%',
        changeType: 'positive',
        changeIcon: 'el-icon-caret-top',
        progress: 90
      }
    ]

    recentArticles.value = articlesRes.data || []
    popularArticles.value = popularRes.data || []
    categoryStats.value = categoryRes.data || []
    weeklyStats.value = weeklyRes.data || []

    nextTick(() => {
      initWeeklyChart()
      initCategoryChart()
      mountResizeObserver()
    })
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

// 初始化周统计图表
const initWeeklyChart = () => {
  if (!weeklyChart.value) return
  weeklyChartInstance = echarts.init(weeklyChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(50, 50, 50, 0.95)',
      borderColor: 'rgba(50, 50, 50, 0.95)',
      textStyle: { color: '#fff', fontSize: 12 }
    },
    grid: { left: '3%', right: '4%', bottom: '8%', top: '8%', containLabel: true },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: weeklyStats.value.map(i => i.date) || [],
      axisLine: { lineStyle: { color: '#e4e7ed' } },
      axisLabel: { color: '#909399', fontSize: 10 }
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { color: '#909399', fontSize: 10 },
      splitLine: { lineStyle: { color: '#f5f7fa' } }
    },
    series: [{
      name: '文章数量',
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 4,
      lineStyle: {
        width: 2,
        color: { type: 'linear', x:0, y:0, x2:1, y2:0,
          colorStops: [{ offset: 0, color: '#667eea' }, { offset: 1, color: '#764ba2' }]
        }
      },
      areaStyle: {
        color: { type: 'linear', x:0, y:0, x2:0, y2:1,
          colorStops: [{ offset: 0, color: 'rgba(102,126,234,.6)' }, { offset: 1, color: 'rgba(118,75,162,.1)' }]
        }
      },
      data: weeklyStats.value.map(i => i.count) || []
    }]
  }
  weeklyChartInstance.setOption(option)
}

// 初始化栏目分布图表
const initCategoryChart = () => {
  if (!categoryChart.value) return
  categoryChartInstance = echarts.init(categoryChart.value)
  const colors = ['#667eea', '#f093fb', '#4facfe', '#43e97b', '#f6d365', '#fda085']
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)',
      backgroundColor: 'rgba(50, 50, 50, 0.95)',
      borderColor: 'rgba(50, 50, 50, 0.95)',
      textStyle: { color: '#fff', fontSize: 11 }
    },
    legend: {
      orient: 'vertical',
      right: '6%',
      top: 'center',
      textStyle: { fontSize: 10, color: '#606266' }
    },
    series: [{
      name: '文章数量',
      type: 'pie',
      radius: ['30%', '65%'],
      center: ['35%', '50%'],
      data: (categoryStats.value || []).map((item, idx) => ({
        value: item.count,
        name: item.name,
        itemStyle: { color: colors[idx % colors.length] }
      })),
      emphasis: { itemStyle: { shadowBlur: 15, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,.3)' } },
      label: { show: false }
    }]
  }
  categoryChartInstance.setOption(option)
}

// 工具函数
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
}
const getStatusType = (status) => ({ published:'success', draft:'info', archived:'warning' }[status] || 'info')
const getStatusText = (status) => ({ published:'已发布', draft:'草稿', archived:'已归档' }[status] || '草稿')
const getRankClass = (index) => (index===0?'gold':index===1?'silver':index===2?'bronze':'')

// 导航
const handleNavigation = (path) => router.push(path)
const handleArticleClick = (articleId) => router.push(`/archives/edit/${articleId}`)

// 生命周期
onMounted(() => {
  loadDashboardData()
  const handleResize = () => {
    if (weeklyChartInstance) weeklyChartInstance.resize()
    if (categoryChartInstance) categoryChartInstance.resize()
  }
  window.addEventListener('resize', handleResize)
  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize)
    if (ro) { try { ro.disconnect() } catch (_) {} }
    if (weeklyChartInstance) weeklyChartInstance.dispose()
    if (categoryChartInstance) categoryChartInstance.dispose()
  })
})
</script>

<style scoped>
/* 全局防溢出：彻底消除横向滚动条；常规页面不出现纵向滚动 */
:global(html), :global(body) {
  overflow-x: hidden;
}
.dashboard-container {
  padding: 12px;
  background: #f0f2f5;
  /* 去掉强制撑高，避免出现多余空间导致滚动 */
  /* min-height: 100vh;  */
  box-sizing: border-box;
}

/* 统计卡片 */
.stats-cards { margin-bottom: 12px; }
.stat-card {
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  background: #fff;
  overflow: hidden;
  transition: transform .2s ease, box-shadow .2s ease;
}
.stat-card:hover { transform: translateY(-2px); box-shadow: 0 8px 20px rgba(0,0,0,.08); }
.stat-item { display: flex; justify-content: space-between; align-items: center; padding: 12px; }
.stat-left { flex: 1; min-width: 0; }
.stat-number { font-size: 22px; font-weight: 700; color: #2c3e50; margin-bottom: 4px; line-height: 1; }
.stat-label { font-size: 12px; color: #909399; font-weight: 500; }
.stat-right { display: flex; flex-direction: column; align-items: center; gap: 6px; }
.stat-icon { width: 38px; height: 38px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 16px; box-shadow: 0 4px 12px rgba(0,0,0,.12); }
.stat-change { font-size: 10px; font-weight: 600; padding: 2px 6px; border-radius: 10px; background: rgba(39,174,96,.08); color: #27ae60; }
.stat-progress { height: 3px; background: #f5f7fa; }
.progress-bar { height: 100%; transition: width .3s ease; }

/* 卡片 */
.chart-card, .content-card, .sidebar-card {
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  background: #fff;
  margin-bottom: 12px;
  /* 关键：不强制高度，避免内部滚动条 */
  height: auto;
}
.card-header {
  display: flex; justify-content: space-between; align-items: flex-start;
  padding: 12px; border-bottom: 1px solid #f5f7fa;
}
.header-left h3 { margin: 0 0 4px 0; font-size: 14px; font-weight: 600; color: #2c3e50; }
.header-left p { margin: 0; font-size: 11px; color: #909399; }
.view-all-btn { color: #909399; font-size: 11px; padding: 4px 8px; }

/* 图表 - 用 clamp 控制高度，防止小屏撑爆产生滚动 */
.chart-container {
  /* 高度在 160px~260px 之间，随视口高度变化 */
  height: clamp(160px, 28vh, 260px);
  width: 100%;
  padding: 0 12px 12px 12px;
}

/* 最新文章列表 - 固定条数，避免滚动 */
.article-list { padding: 0 12px 12px 12px; }
.article-item {
  display: flex; justify-content: space-between; align-items: center;
  padding: 10px 0; border-bottom: 1px solid #f5f7fa; cursor: pointer; transition: transform .15s ease, background .15s ease;
}
.article-item:hover { background: #f8f9fa; transform: translateX(2px); }
.article-item:last-child { border-bottom: none; }
.article-info { flex: 1; min-width: 0; }
.article-title { font-size: 13px; font-weight: 600; color: #2c3e50; margin: 0 0 6px 0; line-height: 1.4; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.article-meta { display: flex; gap: 8px; font-size: 11px; color: #909399; }
.category { background: #f0f9ff; color: #0284c7; padding: 2px 6px; border-radius: 8px; font-size: 10px; }

/* 侧边栏 */
.sidebar-card { margin-bottom: 12px; }
.rank-list { padding: 0 12px 12px 12px; }
.rank-item {
  display: flex; align-items: center; padding: 8px 0;
  border-bottom: 1px solid #f5f7fa; cursor: pointer; transition: transform .15s ease, background .15s ease;
}
.rank-item:hover { background: #f8f9fa; transform: translateX(2px); }
.rank-item:last-child { border-bottom: none; }
.rank-number { width: 22px; height: 22px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: 700; color: #fff; background: #909399; margin-right: 10px; flex-shrink: 0; }
.rank-number.gold { background: linear-gradient(135deg,#ffd700,#ffed4e); color: #b45309; }
.rank-number.silver { background: linear-gradient(135deg,#c0c0c0,#e5e7eb); color: #4b5563; }
.rank-number.bronze { background: linear-gradient(135deg,#cd7f32,#d97706); color:#fff; }
.rank-content { flex: 1; min-width: 0; }
.rank-title { font-size: 12px; font-weight: 600; color: #2c3e50; margin-bottom: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.rank-meta { display: flex; justify-content: space-between; font-size: 10px; color: #909399; }
.views { color: #67c23a; font-weight: 600; }

/* 系统状态 */
.status-list { padding: 0 12px 12px 12px; }
.status-item { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid #f5f7fa; }
.status-item:last-child { border-bottom: none; }
.status-info { display: flex; flex-direction: column; gap: 2px; }
.status-label { font-size: 12px; color: #606266; }
.status-value { font-size: 13px; font-weight: 600; color: #2c3e50; }
.status-indicator { width: 6px; height: 6px; border-radius: 50%; }
.status-indicator.success { background: #67c23a; box-shadow: 0 0 4px rgba(103,194,58,.5); }
.status-progress { width: 48px; height: 4px; background: #f5f7fa; border-radius: 2px; overflow: hidden; }
.progress-fill { height: 100%; background: linear-gradient(135deg,#67c23a,#85ce61); border-radius: 2px; transition: width .3s ease; }

/* 响应式优化：逐步压缩而不是产生滚动 */
@media (max-width: 1200px) {
  .chart-container { height: clamp(150px, 26vh, 220px); }
  .stat-number { font-size: 20px; }
}
@media (max-width: 768px) {
  .dashboard-container { padding: 8px; }
  .stats-cards .el-col, .main-content .el-col { margin-bottom: 10px; }
  .chart-container { height: clamp(140px, 24vh, 200px); padding: 0 10px 10px 10px; }
  .card-header { padding: 10px; }
  .stat-item { padding: 10px; }
  .stat-icon { width: 34px; height: 34px; font-size: 14px; }
  .stat-number { font-size: 18px; }
}
@media (max-width: 480px) {
  .charts-section .el-col { margin-bottom: 10px; }
  .stat-number { font-size: 17px; }
  .article-title, .rank-title { font-size: 11px; }
}

/* 防止任意元素撑破布局导致横向滚动 */
* { box-sizing: border-box; min-width: 0; }
.el-card { height: auto; overflow: visible; }

</style>